package com.bosssoft.rbac.service.impl;

import com.bosssoft.rbac.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bosssoft.rbac.domain.SysPrivilege;
import com.bosssoft.rbac.mapper.SysPrivilegeMapper;
import com.bosssoft.rbac.service.SysPrivilegeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.Set;

/**
 * @ProjectName boss-rbac
 * @Description TODO
 * @author MaYunFei
 * @time 2022/7/5 19:26
 */

@Service
public class SysPrivilegeServiceImpl extends ServiceImpl<SysPrivilegeMapper, SysPrivilege> implements SysPrivilegeService {
    @Autowired
    private SysPrivilegeMapper sysPrivilegeMapper ;

    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**
     * 获取该菜单下面所有的权限
     *
     * @param menuId 菜单的ID
     * @param roleId roleId 代表当前的查询的角色的ID
     * @return
     */
    @Override
    public List<SysPrivilege> getAllSysPrivilege(Long menuId, Long roleId) {
        // 1 查询所有的该菜单下的权限
        List<SysPrivilege> sysPrivileges = list(new LambdaQueryWrapper<SysPrivilege>().eq(SysPrivilege::getMenuId, menuId));
        if(CollectionUtils.isEmpty(sysPrivileges)){
            return Collections.emptyList() ;
        }
        // 2 当前传递的角色使用包含该权限信息也要放进去
        for (SysPrivilege sysPrivilege : sysPrivileges) {
            Set<Long>  currentRoleSysPrivilegeIds = sysPrivilegeMapper.getPrivilegesByRoleId(roleId)  ;
            if (currentRoleSysPrivilegeIds.contains(sysPrivilege.getId())){
                sysPrivilege.setOwn(1); // 当前的角色是否有该权限
            }

        }
        return sysPrivileges;
    }

    @Override
    public List<Long> getMenuIdByPrivilegeId(Long privilegeId) {
        List<Long> ids = new ArrayList<>();
        Long menuId = sysPrivilegeMapper.getMenuIdByPrivilegeId(privilegeId);
        String parentKey = sysMenuMapper.selectParentKey(menuId);
        String[] keys = parentKey.split("\\.");
        ids.add(menuId);
        for (String key : keys) {
            ids.add(Long.valueOf(key));
        }
        return ids;
    }
}
